package com.zhaozhaonews.search.service.impl;


import com.zhaozhaonews.model.common.dto.ResponseResult;
import com.zhaozhaonews.model.common.enums.AppHttpCodeEnum;
import com.zhaozhaonews.model.serach.dto.UserSearchDto;
import com.zhaozhaonews.model.serach.entity.ApAssociateWords;
import com.zhaozhaonews.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author WanJl
 * @version 1.0
 * @title ApAssociateWordsServiceImpl
 * @description
 * @create 2025/2/22
 */
@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 联想词搜索
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findAssociateWords(UserSearchDto userSearchDto) {
        //1、检查参数
        if (userSearchDto==null|| StringUtils.isBlank(userSearchDto.getSearchWords()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //2、分页检查
        if (userSearchDto.getPageSize()>20){
            userSearchDto.setPageSize(20);
        }
        //获取用户输入的关键词
        String searchWords = userSearchDto.getSearchWords();
        //转义搜索关键词，把特殊符号都转义为普通符号，比如* .等
        String escapedSearchWords = java.util.regex.Pattern.quote(searchWords);
        //组成正则表达式，无论中英文标点符号都能匹配
        String regex = ".*" + escapedSearchWords + ".*";
        //3、执行查询，进行模糊查询
        Query query = Query.query(
                Criteria.where("associateWords")
                        .regex(regex,"i")
        );
        query.limit(userSearchDto.getPageSize());
        List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);

        return ResponseResult.okResult(wordsList);
    }
}
